package org.ns.learn.db.autoconf;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public class DBSourceWrapper implements DataSource {
    private HikariDataSource dataSource;

    private HikariConfig config;

    public DBSourceWrapper(HikariConfig config) {
        this.config = config;
    }

    public void restart(HikariConfig config) {
        this.config = config;
        if (this.dataSource != null) {
            restart();
        }
    }

    public void restart() {
        synchronized (this) {
            if (this.dataSource != null && !this.dataSource.isClosed()) {
                try {
                    this.dataSource.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (config != null) {
                this.dataSource = new HikariDataSource(config);
            }
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return dataSource.getConnection(username, password);
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return dataSource.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return dataSource.isWrapperFor(iface);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return dataSource.getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        dataSource.setLogWriter(out);
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        dataSource.setLoginTimeout(seconds);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return dataSource.getLoginTimeout();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {

        return dataSource.getParentLogger();
    }

    public HikariDataSource getDataSource() {
        return dataSource;
    }

    public void close() {
        synchronized (this) {
            if (this.dataSource != null && !this.dataSource.isClosed()) {
                try {
                    this.dataSource.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean isClose() {
        return dataSource == null || dataSource.isClosed();
    }

    public HikariConfig getConfig() {
        return config;
    }
}
